package priv.liaohaolong.fullstacktest.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import priv.liaohaolong.fullstacktest.service.CaptchaService;

import java.io.IOException;

@Component
public class CaptchaValidationFilter extends OncePerRequestFilter {

    private final CaptchaService captchaService;

    @Autowired
    public CaptchaValidationFilter(CaptchaService captchaService) {
        this.captchaService = captchaService;
    }

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        logger.info("Captcha Validation Filter: " + request.getMethod() + " " + request.getRequestURI());

        if ("POST".equals(request.getMethod()) && "/login".equals(request.getRequestURI())) {
            String captchaId = request.getParameter("captchaId");
            String captchaText = request.getParameter("captchaText");

            if (captchaId == null || captchaText == null || !captchaService.verify(captchaId, captchaText)) {
                logger.info("Captcha Validation Filter: Captcha verification failed");

                // response.sendError(HttpServletResponse.SC_BAD_REQUEST); // 不要使用这种方法，这种方法会将请求转发到 /error
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // 400
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\": 400, \"message\": \"验证码无效或缺失\"}");
                response.getWriter().flush(); // 确保响应立即发送
                return;
            }

            logger.info("Captcha Validation Filter: Captcha verification passed");
        }

        filterChain.doFilter(request, response);
    }

}
